<template>
  <div class="app-container">
    <Tabs :list="tabsData" :reorganizeList="reorganizeList" :outOfStorageList="outOfStorageList" :reset="reset"
          @changeStatus="changeStatus" @changeReorganize="changeReorganize"
          @changeOutOfStorage="changeOutOfStorage"/>
    <Search-content :queryParams="queryParams" labelWidth="145px" @query="handleQuery" @reset="resetQuery">

      <el-col :span="6">
        <el-form-item label="车牌号:">
          <el-input v-model="queryParams.carNo" clearable placeholder="请输入车牌号"/>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="车架号:">
          <el-input v-model="queryParams.vinNo" clearable placeholder="请输入车架号"/>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="客户名称:">
          <el-input v-model="queryParams.customerName" clearable placeholder="请输入客户名称"/>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="品牌/车系/车型:">
          <linkage-select @changeNode="linkageChange" v-model="linkageList" placeholder="请选择品牌/车系/车型"
                          style="width: 100%;"/>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="车辆产权:" prop="propertyRightId">
          <el-select filterable v-model="queryParams.propertyRightId" placeholder="请选择车辆产权" clearable
                     style="width: 100%">
            <el-option v-for="item in companyOriginList" :label="item.deptName" :value="item.deptId"
                       :key="item.deptId"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="车辆归属:" prop="ascriptionId">
          <el-select filterable v-model="queryParams.ascriptionId" placeholder="请选择车辆归属" clearable
                     style="width: 100%">
            <el-option v-for="item in companyOriginList" :label="item.deptName" :value="item.deptId"
                       :key="item.deptId"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="车辆运营:" prop="operationsName">
          <el-input v-model="queryParams.operationsName" clearable placeholder="请输入车辆运营"/>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="车辆大区:" prop="cityId">
          <city-select v-model="citySelection2" placeholder="请选择车辆大区" ref="citySelect"
                       :showAllLevels="false"
                       @change="citySelectionChange2"/>
        </el-form-item>
      </el-col>

    </Search-content>

    <div class="card-wrap card-padding">
      <div class="table-title-wrap justify-end">
<!-- todo 先注释 -->
<!--        <e-button type="primary" size="mini" v-hasPermi="['vehicleFiles:vehicleFiles:transfer']" @click="handleTransfer">内部过户-->
<!--        </e-button>-->
<!--        <e-button type="primary" size="mini" v-hasPermi="['vehicleFiles:vehicleFiles:allocate']" @click="handleAllocate">内部调拨-->
<!--        </e-button>-->
        <e-button type="primary" size="mini" v-hasPermi="['vehicleFiles:vehicleFiles:derive']" @click="handleExport">导出
        </e-button>
        <!-- <e-button type="warning" plain icon="el-icon-download" size="mini" v-hasPermi="['demo:demo:export']"
           >新增</e-button> -->

      </div>
      <table-page :loading="loading" :dataList="dataList" :total="total" :page.sync="queryParams.pageNum"
                  :limit.sync="queryParams.pageSize" @setSizeCurrent="getList" border @selectionChange="selectionChange"
                  @selection-change="selectionChange">
        <template slot="tableColAc">
          <el-table-column label="操作" align="center" fixed="left" width="220">
            <template #default="{row}">
                <!-- todo 先注释 -->
<!--              <el-button size="mini" type="text" @click="_toPage({-->
<!--                                                          name: 'TransferAdd',-->
<!--                                                          query: {-->
<!--                                                                carIds:row.carId,-->
<!--                                                                type: 'write',-->
<!--                                                                pageType:'内部过户申请'-->
<!--                                                            }-->
<!--                })" v-if="row.businessType==7 || row.businessType== 8 ||-->
<!--                                    row.businessType==9 || row.businessType== 10 || row.businessType==11 || row.businessType== 12 ||-->
<!--                                    row.businessType==13 || row.businessType== 14 || row.businessType== 15 || row.businessType== 16 || row.businessType== 17"-->
<!--                         v-hasPermi="['vehicleFiles:vehicleFiles:transfer']">内部过户-->
<!--              </el-button>-->
<!--              <el-button size="mini" type="text" @click="_toPage({-->
<!--                                                          name: 'AllocateAdd',-->
<!--                                                          query: {-->
<!--                                                                carIds:row.carId,-->
<!--                                                                type: 'write',-->
<!--                                                                pageType:'内部调拨申请'-->
<!--                                                            }-->
<!--                })" v-if="row.businessType==7 || row.businessType== 8 ||-->
<!--                                    row.businessType==9 || row.businessType== 10 || row.businessType==11 || row.businessType== 12 ||-->
<!--                                    row.businessType==13 || row.businessType== 14 || row.businessType== 15 || row.businessType== 16 || row.businessType== 17"-->
<!--                         v-hasPermi="['vehicleFiles:vehicleFiles:allocate']">内部调拨-->
<!--              </el-button>-->
              <el-button size="mini" type="text" @click="viewOpen(row)"
                         v-hasPermi="['vehicleFiles:vehicleFiles:view']">查看
              </el-button>

              <el-button size="mini" type="text" v-hasPermi="['vehicleFiles:vehicleFiles:dele']"
                         @click="handleDele(row)">删除
              </el-button>
              <!--              <el-button size="mini" type="text" v-hasPermi="['vehicleFiles:vehicleFiles:listing']" v-if="row.carNo != ''"-->
              <!--                @click="handleWork(row)">上架</el-button>-->

            </template>
          </el-table-column>
        </template>

        <template slot="tableCol">
            <!-- todo 先注释 是否多选
             支持发起对应的车辆状态为
             “已还车-闲置7、替代车14、已还车-旧车待出库15、已还车-待确认报废16、已还车-待确认租购过户17、
             处置中8、已处置9、待报废10、已报废11、待过户12、已过户13、维修中、保养中、更换轮胎中、年检中”
             -->
<!--            <el-table-column-->
<!--                type="selection"-->
<!--                width="55"-->
<!--                align="center"-->
<!--                :selectable="row=>row.businessType==7 || row.businessType== 8 ||-->
<!--                                    row.businessType==9 || row.businessType== 10 || row.businessType==11 || row.businessType== 12 ||-->
<!--                                    row.businessType==13 || row.businessType== 14 || row.businessType== 15 || row.businessType== 16 || row.businessType== 17-->
<!--                            "-->
<!--            />-->
          <el-table-column align="center" show-overflow-tooltip label="车牌号" min-width="100" prop="carNo">
            <template #default="{row}">
              <span style="color: #409EFF;">{{ row.carNo }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" show-overflow-tooltip label="车辆来源" width="120" prop="car_source">
            <template #default="{row}">
              {{ selectDictLabel(dict.type.car_source, row.source) }}
            </template>
          </el-table-column>

          <el-table-column align="center" show-overflow-tooltip label="车辆状态" width="100">
            <template #default="{row}">
              {{ selectDictLabel(dict.type.car_business_type, row.businessType) }}
            </template>
          </el-table-column>
          <el-table-column align="center" show-overflow-tooltip label="上牌状态" width="100">
            <template #default="{row}">
              {{ selectDictLabel(dict.type.license_plate_status, row.licensePlateStatus) }}
            </template>
          </el-table-column>
          <el-table-column align="center" show-overflow-tooltip label="购置税状态" width="100">
            <template #default="{row}">
              {{ selectDictLabel(dict.type.purchase_tax_status, row.purchaseTaxStatus) }}
            </template>
          </el-table-column>
          <el-table-column align="center" show-overflow-tooltip label="保险状态" width="100">
            <template #default="{row}">
              {{ selectDictLabel(dict.type.insurance_status_car, row.insuranceStatus) }}
            </template>
          </el-table-column>
          <el-table-column align="center" show-overflow-tooltip label="装饰状态" width="100">
            <template #default="{row}">
              {{ selectDictLabel(dict.type.decorate_status, row.decorateStatus) }}
            </template>
          </el-table-column>

          <el-table-column align="center" show-overflow-tooltip label="车架号" prop="vinNo" min-width="180"/>
          <el-table-column align="center" label="品牌/车型" show-overflow-tooltip width="280">
            <template #default="{row}">
              {{ row.brandName }}{{ row.modelName ? '/' + row.modelName : '' }}
            </template>
          </el-table-column>
          <el-table-column align="center" show-overflow-tooltip label="车辆类型" width="100">
            <template #default="{row}">
              {{ selectDictLabel(dict.type.car_type, row.decorateStatus) }}
            </template>
          </el-table-column>
          <el-table-column align="center" show-overflow-tooltip label="燃油类型" width="100">
            <template #default="{row}">
              {{ selectDictLabel(dict.type.fuel_type, row.fuelType) }}
            </template>
          </el-table-column>
          <el-table-column align="center" show-overflow-tooltip label="车辆产权" width="120"
                           prop="propertyRightName"/>
          <el-table-column align="center" show-overflow-tooltip label="车辆归属" width="120" prop="ascription"/>
          <el-table-column align="center" show-overflow-tooltip label="车辆运营" width="120" prop="operationsName"/>
          <el-table-column align="center" show-overflow-tooltip label="车辆大区" width="120" prop="region"/>
          <el-table-column align="center" show-overflow-tooltip label="客户" min-width="250" prop="customerName"/>
<!--          <el-table-column align="center" show-overflow-tooltip label="新车/二手车" width="120"-->
<!--                           prop="carClassification"/>-->
<!--          <el-table-column align="center" show-overflow-tooltip label="租赁类型" width="100">-->
<!--            <template #default="{row}">-->
<!--              {{ selectDictLabel(dict.type.contract_type, row.contractType) }}-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column align="center" show-overflow-tooltip label="采购完成时间" width="150" prop="createTime"/>
          <el-table-column align="center" show-overflow-tooltip label="公里数" width="120" prop="mileage"/>
          <el-table-column align="center" show-overflow-tooltip label="GPS定位" width="120" prop="gps"/>
          <el-table-column align="center" show-overflow-tooltip label="GPS状态" width="120" prop="gpsStatus">
            <template #default="{row}">
              {{ selectDictLabel(dict.type.gps_status_type, row.gpsStatus) }}
            </template>
          </el-table-column>
        </template>
      </table-page>
    </div>
  </div>
</template>

<script>
import {
  getDataList,
  getHomeCount,
  deleteDataList,
} from "@/api/zcwh/vehicleFilesaApi.js";
import {listDept} from "@/api/system/dept";
import {getToken} from "@/utils/auth";

import LinkageSelect from "../../components/linkageSelect";
//   import ShortcutDate from "../components/ShortcutDate";
import CitySelect from "../../components/citySelect.vue";
import SearchContent from "@/components/SearchContent/index.vue";
import Tabs from "./components/tabs/index.vue";

export default {
  name: "vehicleFiles",

  dicts: [
    "car_source",
    "car_business_type",
    "license_plate_status",
    "purchase_tax_status",
    "insurance_status_car",
    "decorate_status",
    "contract_type",
    "work_order_status",
    "gps_status_type",
    "fuel_type",
    "car_type"
  ],
  components: {
    LinkageSelect,
    CitySelect,
    SearchContent,
    Tabs,
    // 'e-select': ESelect,
  },
  computed: {
    selectDictLabel() {
      return function (arr, val) {
        return arr
            .map((a) => {
              if (a.value == val) {
                return a.label;
              }
            })
            .filter((a) => a)[0];
      };
    },
  },
  data() {
    return {
        selected: [],
      linkageList: [],
      dateValue: [],
      citySelection1: [],
      citySelection2: [],
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        carNo:"",
        vinNo: "",
        brandName: "",
        seriesName: "",
        modelName: "",
        brandId: "",
        seriesId: "",
        modelId: "",
        propertyRightId: "",
        ascriptionId: "",
        operationsName: "",
        cityId: "",
        customerName:""
      },

      total: 0,
      dataList: [],
      reorganizeList: [
        {label: "购置税", value: "purchaseTaxStatus", count: 0},
        {label: "上牌", value: "licensePlateStatus", count: 0},
        {label: "GPS", value: "gpsStatus", count: 0},
        {label: "装饰", value: "decorateStatus", count: 0},
        {label: "保险", value: "insuranceStatus", count: 0},
      ],
      tabsData: [
        {label: "全部车辆", value: "", count: 0},
        {label: "新车待分配", value: "0", count: 0},
        {label: "待整备", value: "1", count: 0},
        {label: "整备中", value: "2", count: 0},
        {label: "待入库", value: "3", count: 0},
        {label: "待出库", value: "4", count: 0},
        {label: "已出库", value: "5", count: 0},
        {label: "待还车", value: "6", count: 0},
        {label: "已还车", value: "7", count: 0},
        {label: "处置中", value: "8", count: 0},
        {label: "已处置", value: "9", count: 0},
        {label: "待报废", value: "10", count: 0},
        {label: "已报废", value: "11", count: 0},
        {label: "待过户", value: "12", count: 0},
        {label: "已过户", value: "13", count: 0},

        {label: "替代车", value: "14", count: 0},
        {label: "已还车-待确认报废", value: "16", count: 0},
        {label: "已还车-待确认租购过户", value: "17", count: 0},
        {label: "已还车-旧车待出库", value: "15", count: 0},
      ],
      outOfStorageList: [
        {label: "维修中", value: "maintenanceStatus", count: 0},
        {label: "保养中", value: "maintainStatus", count: 0},
        {label: "更换轮胎中", value: "replaceTyreStatus", count: 0},
        {label: "年检中", value: "inspectionStatus", count: 0},
      ],
      reset: 0,
      companyOriginList: [],
    };
  },
  created() {
    this.getList();
    this.handleCount();
    this.getCompanyOrigin();
  },
  mounted() {
  },
  methods: {
    getCompanyOrigin() {
      listDept({
        deptType: "2", //组织类型（1部门 2公司）
        regionId: null, //所在城市（省市区id）
      }).then((res) => {
        this.companyOriginList = res.data;
        this.belongCompanyList = res.data;
      });
    },

    handleCount() {
      getHomeCount().then((res) => {
        for (let key in res) {
          //车辆状态
          let index = this.tabsData.findIndex((a) => a.label === key);
          if (index !== -1) {
            this.tabsData[index].count = res[key];
          }

          //整备中
          let index_ = this.reorganizeList.findIndex((a) => a.label === key);
          if (index_ !== -1) {
            this.reorganizeList[index_].count = res[key];
          }

          //已出库
          let _index = this.outOfStorageList.findIndex((a) => a.label === key);
          if (_index !== -1) {
            this.outOfStorageList[_index].count = res[key];
          }
        }
      });
    },

    changeDate(val) {
      if (val) {
        this.queryParams.createStartTime = val[0];
        this.queryParams.createEndTime = val[1];
        this.queryParams.violaTimeStatus = "";
      } else {
        this.queryParams.createStartTime = "";
        this.queryParams.createEndTime = "";
      }
    },
    citySelectionChange1(val) {
      this.queryParams.ascriptionId = val[0].value;
    },

    citySelectionChange2(val) {
      this.queryParams.cityId = val[0].value;
    },

    linkageChange(val) {
      this.linkageList = val;
      if (val) {
        // this.queryParams.brandName = val[0] ? val[0].name : "";
        // this.queryParams.seriesName = val[1] ? val[1].name : "";
        // this.queryParams.modelName = val[2] ? val[2].name : "";
        this.queryParams.brandId = val[0] ? val[0].id : "";
        this.queryParams.seriesId = val[1] ? val[1].id : "";
        this.queryParams.modelId = val[2] ? val[2].id : "";
      } else {
        this.queryParams.brandName = "";
        this.queryParams.seriesName = "";
        this.queryParams.modelName = "";
        this.queryParams.brandId = "";
        this.queryParams.seriesId = "";
        this.queryParams.modelId = "";
      }
      this.$forceUpdate();
    },
    /** 查询测试单表列表 */
    getList() {
      this.loading = true;
      getDataList(this.queryParams)
          .then((res) => {
            if (res.code == "200") {
              const {rows, total} = res;
              this.dataList = rows;
              this.total = total;
              this.loading = false;
            }
          })
          .catch(() => {
            this.loading = false;
          });
    },

    changeStatus(val) {
      this.queryParams.purchaseTaxStatus = "";
      this.queryParams.licensePlateStatus = "";
      this.queryParams.gpsStatus = "";
      this.queryParams.decorateStatus = "";
      this.queryParams.insuranceStatus = "";
      this.queryParams.businessType = "";
      this.queryParams.businessType = val;
      this.queryParams.pageNum = 1;
      this.getList();
    },
    changeReorganize(val) {
      this.queryParams.purchaseTaxStatus = "";
      this.queryParams.licensePlateStatus = "";
      this.queryParams.gpsStatus = "";
      this.queryParams.decorateStatus = "";
      this.queryParams.insuranceStatus = "";
      this.queryParams.businessType = "";
      this.queryParams[val] = 3;
      this.queryParams.pageNum = 1;
      this.getList();
    },

    changeOutOfStorage(val) {
      this.queryParams.maintenanceStatus = "";
      this.queryParams.maintainStatus = "";
      this.queryParams.replaceTyreStatus = "";
      this.queryParams.inspectionStatus = "";
      this.queryParams[val] = 2
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        carNo:"",
        vinNo: "",
        brandName: "",
        seriesName: "",
        modelName: "",
        brandId: "",
        seriesId: "",
        modelId: "",
        propertyRightId: "",
        ascriptionId: "",
        operationsName: "",
        cityId: "",
        customerName:""
      };
      this.citySelection1 = []
      this.citySelection2 = []
      this.reset++;
      this.getList();
    },

      selectionChange(val) {
          this.selected = val;
      },

    viewOpen(row, type) {
      this.$router.push({
        path: "/clgl/vehicleDetails",
        query: {
          carId: row.carId,
        },
      });
    },

    handleDele(row) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
          .then(() => {
            deleteDataList(row.carId).then((res) => {
              if (res.code === 200) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                this.queryParams.pageNum = 1;
                this.getList();
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
    },

    handleWork(row) {
      if (row.businessDataId) {
        this.$router.push({
          path: "/cwgd/replaceTireDetails",
          query: {
            id: row.id,
            businessDataId: row.businessDataId,
          },
        });
      } else {
        this.$router.push({
          path: "/cwgd/replaceTireDetails",
          query: {
            id: row.id,
          },
        });
      }
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
          "/car/carBasic/export",
          {
            ...this.queryParams,
          },
          `车辆档案列表_${new Date().getTime()}.xlsx`
      );
    },

      //调拨
      handleAllocate(){
          if (this.selected?.length == 0) {
              this.$message({
                  message: "请先选择列表",
                  type: "warning",
              });
              return;
          }

          let ascription = this.selected[0].ascription;

          let allSame = this.selected.every(item=>ascription===item.ascription);

          if(!allSame){
              this.$message({
                  message: "所选车辆归属公司需相同",
                  type: "warning",
              });
              return;
          }

          this._toPage({
              name: 'AllocateAdd',
              query: {
                  carIds:this.selected.map(item=>item.carId).join(","),
                  type: 'write',
                  pageType:'内部调拨申请'
              }
          })
      },


    //过户
    handleTransfer(){
      if (this.selected?.length == 0) {
          this.$message({
              message: "请先选择列表",
              type: "warning",
          });
          return;
      }

      //propertyRightId:null  propertyRightName:"近多出行"

        let propertyRightId = this.selected[0].propertyRightId;

        let allSame = this.selected.every(item=>propertyRightId===item.propertyRightId);

        if(!allSame){
            this.$message({
                message: "所选车辆产权公司需相同",
                type: "warning",
            });
            return;
        }

      this._toPage({
          name: 'TransferAdd',
          query: {
              carIds:this.selected.map(item=>item.carId).join(","),
              type: 'write',
              pageType:'内部过户申请'
          }
      })
  },

  },
};
</script>
<style lang="scss" scoped>
</style>
